package com.xuxiang.cloud.java.defcode.sort;

/**
 * @author xuxiang 2020/3/11 16:39
 */
public class Test {

    public void test(int [] s) {
        int len = s.length;
        int p = len / 2;
        while (p > 0) {
            adjust(s, p, len);
            p--;
        }
        int i = len - 1;
        while (i > 0) {
            swap(s, 0, i);
            adjust(s, 1, i);
            i--;
        }

    }


    public void adjust(int [] s, int p, int len) {
        int l = p << 1;
        int r = l + 1;
        int max = s[p-1];
        int maxP = p;
        if (l <= len && s[l-1] > max) {
            maxP = l;
            max = s[l-1];
        }
        if (r <= len && s[r-1] > max) {
            maxP = r;
        }
        if (maxP != p) {
            swap(s, maxP-1, p-1);
            adjust(s, maxP, len);
        }
    }

    private void swap(int [] s, int a, int b) {
        int tmp = s[a];
        s[a] = s[b];
        s[b] = tmp;
    }

}
